package com.bjc.platform.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.bjc.platform.dao.GenericDao;
import com.bjc.platform.service.AdmLogService;
import com.bjc.platform.util.DateUtil;
import com.bjc.platform.util.Page;
import com.bjc.platform.util.SqlUtil;
import com.bjc.platform.vo.AdmLogSearchCondition;

@Service("logService")
public class AdmLogServiceImpl extends BaseServiceImpl implements AdmLogService {

	@Autowired
	private GenericDao genericDao;

	@Override
	public Page search(AdmLogSearchCondition cond, PageRequest pr) {
		Page page = new Page();
		StringBuilder sql = new StringBuilder();
		sql.append("select l.data, l.source,l.event_no eventNo, l.type, l.url, l.func_name,l.description, u.username , DATE_FORMAT(l.log_time,'%Y-%m-%d %T') logTime ");
		sql.append(" from adm_logs l inner join adm_user u on l.user_id = u.id ");
		Map<String, Object> param = new HashMap<String, Object>();
		if (cond != null) {
			if (!StringUtils.isEmpty(cond.getUname())) {
				sql.append(" and u.username like :user");
				param.put("user", SqlUtil.wrapperLike(cond.getUname()));
			}
			if (cond.getFromDate() != null) {
				sql.append(" and l.log_time >= :fromDate");
				param.put("fromDate", cond.getFromDate());
			}

			if (cond.getToDate() != null) {
				Date toDate = DateUtil.getNextDateStartTime(cond.getToDate());
				if (toDate != null) {
					sql.append(" and l.log_time <= :toDate");
					param.put("toDate", toDate);
				}
			}
		}
		sql.append(" order by log_time desc ");

		long count = genericDao.countBySql(sql.toString(), param);
		List result = genericDao.queryBySqlToMap(sql.toString(), param, pr);
		page.setTotalCount(count);
		page.setResult(result);
		return page;
	}
}
